package kind

import (
	"github.com/goravel/framework/facades"
	"goravel/app/models"
)

type KindService struct{}

func NewKindService() *KindService {
	return &KindService{}
}

func (m *KindService) RecursionGet() ([]models.Kind, error) {
	Kinds := []models.Kind{}
	err := facades.Orm().Query().Model(&models.Kind{}).Where("pid=?", 0).With("Children").Find(&Kinds)
	if err != nil {
		return nil, err
	}
	for i := range Kinds {
		m.BuildChildrenRecursively(&Kinds[i])
	}
	return Kinds, nil
}

func (m *KindService) BuildChildrenRecursively(parent *models.Kind) *models.Kind {
	children := []models.Kind{}
	err := facades.Orm().Query().Model(&models.Kind{}).Where("pid =?", parent.ID).Find(&children)
	if err != nil {
		return nil
	}
	parent.Children = children
	for i := range children {
		return m.BuildChildrenRecursively(&children[i])
	}
	return parent
}
